# -*- coding: utf-8 -*-
import FPLib
import os
import importlib
import traceback

JSON = FPLib.lib("Parser.JSON")


class API(object):
    """API."""

    def __init__(self, server):
        super(API, self).__init__()
        self.server = server
        self.isout = False

    def reset(self):
        self.isout = False

    def goto(self, url):
        self.out(True, url, "1")

    def out(self, result=True, msg="", code="0"):
        try:
            if self.isout:
                print("API is Out already")
                return
            self.isout = True
            res = {
                "result": result,
                "code": code,
                "data": msg
            }
            self.header()
            self.server.write(JSON.stringify(res))
            # self.server.flush()
        except Exception as e:
            print("API Out Error:", e)

    def ok(self, msg=""):
        self.out(True, msg)

    def error(self, msg=""):
        self.out(False, msg)

    def header(self):
        self.server.set_header("Cache-Control", "no-cache, must-revalidate")
        self.server.set_header("Pragma", "no-cache")
        self.server.set_header("Content-Type", "application/json; charset=UTF-8")
        # self.server.set_header("Content-Type", "application/json")

    def call_404(self):
        self.server.write("API is missing")
